#!/usr/bin/python
# -*- coding: utf-8 -*-

import Image
import sys


def splitImage(file, output):
	im = Image.open(file)
	nim = im.copy()
	(width, height) = im.size

#1. 2値化
        nim = nim.convert("1")
	
#2. 行SCAN＆統計
	line_sum = []
	pix = nim.load()
	for x in range(height):
		cnt = 0
                for y in range(width):
                       if pix[y, x] == 0:
				cnt = cnt + 1 
		line_sum.append(cnt)

#3. 騒音対策
	min_pix = 65	#決め方要検討
	for x in range(height):
		if ( line_sum[x] <= min_pix ):
			line_sum[x] = 0
		else:
			line_sum[x] = line_sum[x] - min_pix 
		print line_sum[x]


#5. 行分け (zero_counter > 1)
	blocks = []
	tStart = 0
	tEnd   = 0
	bFirst = True
	zero_counter = 0 
	for x in range(height):
		if ( line_sum[x] != 0 ):
			if ( bFirst ) :
				bFirst = False
				tStart = x
			zero_counter = 0
		else:
			if ( not bFirst and zero_counter > 1 ) :
				tEnd = x			
				bFirst = True
				blocks.append((tStart, tEnd))
			zero_counter = zero_counter + 1

#5.5 画像表示
	nim = im.copy()
	pix = nim.load()
	idx = 0
	for s,e in blocks:
		for p in range(width):
			pix[p, s] = 0 
			pix[p, e] = 0
		idx = idx + 1		
	nim.save(output)

#Main処理
if __name__ == '__main__':
        argvs = sys.argv
        argc  = len(argvs)
        if ( argc != 2 ):
                print "Usage: img-tool <FileName>"
                sys.exit(1)
        splitImage(argvs[1], '/tmp/result.pgm')
